package com.aifeng.hassan_food

import android.graphics.Point
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import com.aifeng.base.BaseActivity
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.invisible
import com.aifeng.common_ui.base.oneTouch
import com.aifeng.common_ui.base.visible
import com.aifeng.common_ui.helper.getString
import com.aifeng.common_ui.helper.isLogin
import com.aifeng.fragment.*
import com.aifeng.hassan_food.login.LoginActivity
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeByFinally
import com.aifeng.view.BeizerTextView
import com.aifeng.viewmodel.GoodsViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setTransparentAndToolbar()
        initTitle()
        main_check1.performClick()

        checkCarNum()
    }

    override fun getViewModel() = getViewModel<GoodsViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        main_check1.setOnCheckedChangeListener(this)
        main_check2.setOnCheckedChangeListener(this)
        main_check3.setOnCheckedChangeListener(this)
        main_check4.setOnCheckedChangeListener(this)
        main_check5.setOnCheckedChangeListener(this)

        main_check3.oneTouch(
            handle = { !isLogin && it.action == MotionEvent.ACTION_UP },
            listener = { startActivity<LoginActivity>() }
        )
        main_check4.oneTouch(
            handle = { !isLogin && it.action == MotionEvent.ACTION_UP },
            listener = { startActivity<LoginActivity>() }
        )
        main_check5.oneTouch(
            handle = { !isLogin && it.action == MotionEvent.ACTION_UP },
            listener = { startActivity<LoginActivity>() }
        )

        observe("loginStatus") {
            when (it) {
                "home" -> main_check1.performClick()
                "quit" -> {
                    main_num.invisible()
                    main_num.text = "0"
                    main_check1.performClick()
                }
                "login" -> {
                    checkCarNum()
                    LiveEventBus.get("carList").post("refresh")
                    LiveEventBus.get("saleList").post("refresh")
                }
            }
        }

        observe("updateNum") {
            if ("," !in it) {
                if (it != "{}") {
                    main_num.text = it
                    main_num.visibility = if (it == "0") View.INVISIBLE else View.VISIBLE
                }
            } else {
                val point = it.split(",")
                val endPosition = IntArray(2)
                main_num.getLocationInWindow(endPosition)

                (window.decorView as ViewGroup)
                    .addView(
                        BeizerTextView(baseContext).apply {
                            setStartPosition(
                                Point(
                                    point[0].toInt(),
                                    point[1].toInt()
                                )
                            )

                            setEndPosition(
                                Point(
                                    endPosition[0],
                                    endPosition[1]
                                )
                            )

                            startBeizerAnimation(
                                onFinished = {
                                    if (point[2] != "{}") {
                                        main_num.visible()
                                        main_num.text = point[2]
                                    }
                                }
                            )
                        }
                    )
            }
        }
    }

    private fun checkCarNum() {
        if (isLogin) {
            getViewModel().getCarList(getString("userId"))
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByFinally(
                    event = getViewModel(),
                    onSuccess = {
                        main_num.text = it.size.toString()
                        if (it.size > 0) main_num.visible()
                        else main_num.gone()
                    }
                )
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        // instantiateItem从FragmentManager中查找Fragment，找不到就getItem新建一个，
        // setPrimaryItem设置隐藏和显示，最后finishUpdate提交事务。
        if (isChecked) {
            val fragment = mFragmentPagerAdapter
                .instantiateItem(main_container, buttonView.id) as Fragment
            mFragmentPagerAdapter.setPrimaryItem(main_container, 0, fragment)
            mFragmentPagerAdapter.finishUpdate(main_container)
        }
    }

    @Suppress("DEPRECATION")
    private val mFragmentPagerAdapter =
        object : FragmentPagerAdapter(supportFragmentManager) {

            override fun getItem(position: Int): Fragment = when (position) {
                R.id.main_check1 -> MainOneFragment()
                R.id.main_check2 -> MainTwoFragment()
                R.id.main_check3 -> MainThreeFragment()
                R.id.main_check4 -> MainFourFragment()
                R.id.main_check5 -> MainFiveFragment()
                else -> MainOneFragment()
            }

            override fun getCount(): Int = 5
        }

    private var exitTime: Long = 0
    override fun onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            toast("再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else super.onBackPressed()
    }

}
